const { Service } = require('egg');

class OrderService extends Service {
  // 获取订单数据
  // 参数 query 查询项，根据第几页，从第几条获取数据
  async getOrder(query) {
    try {
      let currentPage = parseInt(query.currentPage);
      let pageSize = parseInt(query.pageSize);
      let offset = (currentPage - 1) * pageSize;
      console.log(currentPage, pageSize, offset);
      return await this.app.model.Order.findAndCountAll({
        order: [
          [ 'createdAt', 'DESC' ]
        ],
        offset,
        limit: pageSize
      });
    } catch (error) {
      return false;
    }
  }
  // 修改订单地址
  async changeOrderAddr(id, newAddress) {
    try {
      await this.app.model.Order.update({
        order_address: newAddress,
      }, {
        where: {
          id
        }
      });
      return true;
    } catch (error) {
      return false;
    }
  }
  // 修改订单发货状态
  async changeOrderState(id, newSendState) {
    try {
      await this.app.model.Order.update({
        order_isSend: newSendState,
      }, {
        where: {
          id
        }
      });
      return true;
    } catch (error) {
      return false;
    }
  }
  // 搜索单号
  async searchOrder(query) {
    try {
      let number = query.number;
      let newArr = [];
      let data = await this.app.model.Order.findAll({
        order: [
          [ 'createdAt', 'DESC' ]
        ]
      });
      data.forEach( item => {
        let dataNumber = item.dataValues.order_number;
        // 如果没有就返回，有就存储
        if (dataNumber.indexOf(number) === -1) {
          return;
        } else {
          newArr.push(item.dataValues);
        }
      });
      return newArr;
    } catch (e) {
      return false;
    }
  }
  // 获取订单数量
  async getOrderNum() {
    return await this.app.model.Order.findAll({
      attributes: [ 'order_number']
    });
  }
}

module.exports = OrderService;
